package com.jml.springsecurity.core.social;

import com.jml.springsecurity.core.properties.SecurityProperties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.security.SpringSocialConfigurer;


@Configuration
@EnableSocial //可以使用spring social
public class SocialConfig extends SocialConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired(required = false)
	private ConnectionSignUp connectionSignUp;

	//UsersConnectionRepositoryspring已经帮我们整好了，这里是需要我们自己配置一下
	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		//第三个参数是加解密，当前没有加减密码
		//建立数据库表，脚本在connectionFactoryLocator包下，表名不可变，但是可加前缀
		//社交用户的信息存在字段providerId，providerUserId。而userid是业务系统用户ID
		JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource,
				connectionFactoryLocator, Encryptors.noOpText());
		//修改表名需要设置前缀
		repository.setTablePrefix("jml_");
		return repository;
	}

	//social过滤链放入springsecurity中
	@Bean
	public SpringSocialConfigurer jmlSocialSecurityConfig() {
		String filterProcessesUrl = securityProperties.getSocial().getFilterProcessesUrl();
		JmlSpringSocialConfigurer configurer = new JmlSpringSocialConfigurer(filterProcessesUrl);
		//configurer.signupUrl(securityProperties.getBrowser().getSignUpUrl());
		return configurer;
	}

	@Bean
	public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator connectionFactoryLocator) {
		return new ProviderSignInUtils(connectionFactoryLocator,
				getUsersConnectionRepository(connectionFactoryLocator)) {
		};
	}

}
